using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;

using KalDev;
using CrmServiceWebReference;
using LtMbs.CrmSdkHelperClass;
namespace LtMbs
{
    /// <summary>
    /// Contacts object, to move data between systems
    /// </summary>
    public class Contact
    {

        private string addressLine1 = "";
        private string addressLine2 = "";
        private string addressLine3 = "";
        private string addressLine4 = "";
        private string country = "";
        private string dateOfBirth = "";
        private string emailAddress = "";
        private string firstName = "";
        private string kmsPassword = "";
        private string languagePreference = "";
        private string lastName = "";
        private string mobileNumber = "";
        private string orderNumber = "";
        private string password = "";
        private string personIdNumber = "";
        private string phoneNumber = "";
        private string title = "";
        private string shopperid = "";

        /// <summary>
        /// Gets or sets the address line1.
        /// </summary>
        /// <value>The address line1.</value>
        internal string AddressLine1
        {
            get { return addressLine1; }
            set { addressLine1 = value; }
        }
        /// <summary>
        /// Gets or sets the address line2.
        /// </summary>
        /// <value>The address line2.</value>
        internal string AddressLine2 { get { return addressLine2; } set { addressLine2 = value; } }
        /// <summary>
        /// Gets or sets the address line3.
        /// </summary>
        /// <value>The address line3.</value>
        internal string AddressLine3 { get { return addressLine3; } set { addressLine3 = value; } }
        /// <summary>
        /// Gets or sets the address line4.
        /// </summary>
        /// <value>The address line4.</value>
        internal string AddressLine4 { get { return addressLine4; } set { addressLine4 = value; } }
        /// <summary>
        /// Gets or sets the country.
        /// </summary>
        /// <value>The country.</value>
        internal string Country { get { return country; } set { country = value; } }
        /// <summary>
        /// Gets or sets the date of birth.
        /// </summary>
        /// <value>The date of birth.</value>
        internal string DateOfBirth { get { return dateOfBirth; } set { dateOfBirth = value; } }
        /// <summary>
        /// Gets or sets the email address.
        /// </summary>
        /// <value>The email address.</value>
        internal string EmailAddress { get { return emailAddress; } set { emailAddress = value; } }
        /// <summary>
        /// Gets or sets the name of the first.
        /// </summary>
        /// <value>The name of the first.</value>
        internal string FirstName { get { return firstName; } set { firstName = value; } }
        /// <summary>
        /// Gets or sets the KMS password.
        /// </summary>
        /// <value>The KMS password.</value>
        internal string KmsPassword { get { return kmsPassword; } set { kmsPassword = value; } }
        /// <summary>
        /// Gets or sets the language preference.
        /// </summary>
        /// <value>The language preference.</value>
        internal string LanguagePreference { get { return languagePreference; } set { languagePreference = value; } }
        /// <summary>
        /// Gets or sets the name of the last.
        /// </summary>
        /// <value>The name of the last.</value>
        internal string LastName { get { return lastName; } set { lastName = value; } }
        /// <summary>
        /// Gets or sets the mobile number.
        /// </summary>
        /// <value>The mobile number.</value>
        internal string MobileNumber { get { return mobileNumber; } set { mobileNumber = value; } }
        /// <summary>
        /// Gets or sets the order number.
        /// </summary>
        /// <value>The order number.</value>
        internal string OrderNumber { get { return orderNumber; } set { orderNumber = value; } }
        /// <summary>
        /// Gets or sets the password.
        /// </summary>
        /// <value>The password.</value>
        internal string Password { get { return password; } set { password = value; } }
        /// <summary>
        /// Gets or sets the person id number.
        /// </summary>
        /// <value>The person id number.</value>
        internal string PersonIdNumber { get { return personIdNumber; } set { personIdNumber = value; } }
        /// <summary>
        /// Gets or sets the phone number.
        /// </summary>
        /// <value>The phone number.</value>
        internal string PhoneNumber
        {
            get
            { return phoneNumber; }
            set { phoneNumber = value; }
        }
        internal string Firstname
        {
            get
            {
                return firstName;
            }
            set
            {
                firstName = value;
            }
        }
        internal string Title
        {
            get
            {
                return title;
            }
            set
            {
                title = value;
            }
        }

        internal string ShopperId
        {
            get
            {
                return shopperid;
            }
            set
            {
                shopperid = value;
            }
        }
        /// <summary>
        /// Creates a CRM Contact, using information from KMS
        /// </summary>
        /// <returns></returns>
        public Guid Create()
        {
            contact crmContactToCreate = new contact();

            crmContactToCreate.firstname = Firstname;
            crmContactToCreate.lastname = LastName;
            crmContactToCreate.telephone1 = PhoneNumber;
            crmContactToCreate.new_languagepreference = LanguagePreference;
            crmContactToCreate.new_password = Password;
            crmContactToCreate.new_idnumber = PersonIdNumber;
            crmContactToCreate.address1_line1 = AddressLine1;
            crmContactToCreate.address1_line2 = AddressLine2;
            crmContactToCreate.address1_line3 = AddressLine3;
            crmContactToCreate.address1_postalcode = AddressLine4;
            crmContactToCreate.address2_country = Country;
            crmContactToCreate.birthdate = CrmTypes.CreateCrmDateTime(DateOfBirth);
            crmContactToCreate.emailaddress1 = EmailAddress;
            crmContactToCreate.new_shopperid = ShopperId;

            CrmService service = new CrmService();
            service.Credentials = new System.Net.NetworkCredential(Resources.Resource.CrmUserName, Resources.Resource.CrmPassword, Resources.Resource.CrmDomain);
            Guid createdContactId = service.Create(crmContactToCreate);
            return createdContactId;

        }
        /// <summary>
        /// Imports the specified contact to CRM.
        /// </summary>
        /// <param name="KmsShopperId">The KMS shopper id.</param>
        /// <returns></returns>
        public static Guid CreateCrmContact(string KmsShopperId)
        {
            return new Contact().createCrmContact(KmsShopperId);
        }
        /// <summary>
        /// Creates the CRM contact, by retreiving the contact information from KMS 
        /// via the web service and then creating the crm contact
        /// and once that has happend successfully, updating KMS, so that the KMS system is aware of this record being integrated.
        /// this does not support transactions,and if the updating of KMS fails, this method would not handle the deleteing of the CRM Record
        /// </summary>
        /// <param name="ShopperId">The shopper id in KMS</param>
        /// <returns></returns>
        private Guid createCrmContact(string ShopperId)
        {
            CrmService service = Common.CrmAutorize();

            Shopper KmsShopper = GetFromKms(ShopperId);

            #region ContactFieldMappings
            contact CrmContactToCreate = new contact();
            CrmContactToCreate.new_street1 = KmsShopper.Address1;
            CrmContactToCreate.new_street2 = KmsShopper.Address2;
            CrmContactToCreate.new_street3 = KmsShopper.Address3;
            CrmContactToCreate.new_street4 = KmsShopper.Address4;
            CrmContactToCreate.mobilephone = KmsShopper.CellPhone;
            CrmContactToCreate.new_country = KmsShopper.Country;
            CrmContactToCreate.birthdate = CrmTypes.CreateCrmDateTime(KmsShopper.Date_of_birth);
            CrmContactToCreate.emailaddress1 = KmsShopper.Email;
            CrmContactToCreate.firstname = KmsShopper.FirstName;
            CrmContactToCreate.new_idnumber = KmsShopper.IdNumber;
            CrmContactToCreate.new_languagepreference = KmsShopper.LanguagePref;
            CrmContactToCreate.lastname = KmsShopper.LastName;
            CrmContactToCreate.new_password = KmsShopper.Password;
            CrmContactToCreate.telephone1 = KmsShopper.Phone;
            CrmContactToCreate.new_shopperid = KmsShopper.ShopperId;
            #endregion ContactFieldMappings

            Guid contactId = service.Create(CrmContactToCreate);
            updateKms(contactId, ShopperId);

            return contactId;
        }
        public static string createUnknownContact(string email, string FirstName, string LastName)
        {
            CrmService contactService = Common.CrmAutorize();
            contact contact = new contact();
            contact.firstname = FirstName;
            contact.lastname = LastName;
            contact.emailaddress1 = email;
            string keyOfCreatedContact = contactService.Create(contact).ToString();
            return keyOfCreatedContact;
        }
        /// <summary>
        /// Updates KMS, with the ContactId (Guid) so that KMS can return the correct results when integration runs
        /// </summary>
        /// <param name="contactId">The contact id of the CRM Contact</param>
        /// <param name="ShopperId">The shopper id, as KMS knows it</param>
        private void updateKms(Guid contactId, string ShopperId)
        {
            CRMService service = Common.KmsAuthorize();
            service.UpdateCRMLink(ShopperId, contactId.ToString());
        }
        /// <summary>
        /// Gets the specified shopper, buy using the KMS Webservice and searching for a shopper id.
        /// If the order of parameters change in the web service, this method will not function correctly
        /// it expects the parameters in the following list (order is important)
        /// <list type="bullet">
        /// <item>Firstname</item>
        /// <item>LastName</item>
        /// <item>Phone Number</item>
        /// <item>Cell number</item>
        /// <item>Email Address</item>
        /// <item>ShopperId</item><remarks>This is the important one</remarks>
        /// <item>OrderID</item>
        /// </list>
        /// </summary>
        /// <param name="ShopperId">The shopper id.</param>
        /// <returns></returns>
        private Shopper GetFromKms(string ShopperId)
        {
            CRMService service = Common.KmsAuthorize();
            SearchResult result = service.SearchShoppers("", "", "", "", "", ShopperId, "");
            return result.Shoppers[0];
        }
        [WebMethod]
        public string createActivityForTestingUse()
        {
            email email = new email();
            email.sender = "test@test.com";
            email.subject = "TestEmail Created by CaseTest.cs";
            email.torecipients = "support@kalahari.net";

            TargetCreateEmail target = new TargetCreateEmail();
            target.Email = email;

            CreateRequest request = new CreateRequest();
            request.Target = target;
            CrmService service = Common.CrmAutorize();
            CreateResponse createdEmail = (CreateResponse)service.Execute(request);

            TargetQueuedEmail emailTarget = new TargetQueuedEmail();
            emailTarget.EntityId = createdEmail.id;

            RouteRequest emailRouterequest = new RouteRequest();
            emailRouterequest.Target = emailTarget;
            emailRouterequest.EndpointId = new Guid(Resources.Resource.SupportQueueId);
            emailRouterequest.RouteType = RouteType.Auto;
            emailRouterequest.SourceQueueId = Common.wipQueue().queueid.Value;
            CrmService routeService = Common.CrmAutorize();
            routeService.Execute(request);

            return createdEmail.id.ToString();
        }
    }
}